<template>
  <base-breadcrumb>
    <a-card
      :bordered="false"
      style="margin-bottom: 20px"
    >
      <title-name title="基础信息" />
      <a-form layout="horizontal">
        <a-row :gutter="24">
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-item
              label="设计资源名称"
              :label-col="{lg: {span: 5}, sm: {span:5}}"
              :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
            >
              <BaseInput
                v-model="dels.designResourceName"
                placeholder=""
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-item
              label="设计资源类型"
              :label-col="{lg: {span: 5}, sm: {span:5}}"
              :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
            >
              <BaseInput
                v-model="dels.designResourceType"
                placeholder=""
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-item
              label="所属单位"
              :label-col="{lg: {span: 5}, sm: {span:5}}"
              :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
            >
              <BaseInput
                v-model="dels.viewName"
                placeholder=""
                disabled
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-item
              label="年度时间"
              :label-col="{lg: {span: 5}, sm: {span:5}}"
              :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
            >
              <BaseInput
                v-model="dels.year"
                placeholder=""
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-item
              label="项目设计管理类别"
              :label-col="{lg: {span: 5}, sm: {span:5}}"
              :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
            >
              <BaseInput
                v-model="dels.designTypeName"
                disabled
              />
            </a-form-item>
          </a-col>
<!--          <a-col-->
<!--            :md="8"-->
<!--            :sm="8"-->
<!--          >-->
<!--            <a-form-item-->
<!--              label="分公司"-->
<!--              :label-col="{lg: {span: 5}, sm: {span:5}}"-->
<!--              :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"-->
<!--            >-->
<!--              <BaseInput-->
<!--                v-model="dels.branchComName"-->
<!--                disabled-->
<!--              />-->
<!--            </a-form-item>-->
<!--          </a-col>-->
        </a-row>
      </a-form>

      <title-name title="分公司评价（设计资源考核评价表）" />
      <a-table
        ref="table"
        :pagination="false"
        bordered
        size="default"
        row-key="key"
        :columns="columnsScore"
        :data-source="tableData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        show-pagination="auto"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <template
          slot="score"
          slot-scope="text, record"
        >
          <BaseInputNumber
            v-model="record[score]"
            style="width:120px"
            :max="getMaxValue(record)"
            :precision="0"
            :formatter="limitNumber"
            :parser="limitNumber"
            :min="0"
            placeholder="请评分"
            @blur="superpositionScore"
          />
        </template>
      </a-table>

      <title-name
        title="审核结果"
        class="marginTop"
      />
      <a-form-model
        ref="form1"
        :model="form"
        :rules="rules"
      >
        <a-row :gutter="24">
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="评价总分数"
              :label-col="{lg: {span: 5}, sm: {span:5}}"
              :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
            >
              <BaseInput
                v-model="dels.totalScore"
                placeholder=""
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="评价人"
              :label-col="{lg: {span: 5}, sm: {span:5}}"
              :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
            >
              <BaseInput
                v-model="dels.creater"
                placeholder=""
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="评价时间"
              :label-col="{lg: {span: 5}, sm: {span:5}}"
              :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
            >
              <BaseInput
                v-model="dels.createTime"
                placeholder=""
                disabled
              />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="评价等级"
              :label-col="{lg: {span: 5}, sm: {span:5}}"
              :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
            >
              <BaseInput
                v-model="dels.assessmentLevel"
                placeholder=""
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="合同范围"
              :label-col="{lg: {span: 5}, sm: {span:5}}"
              :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
              prop="contractScope"
            >
              <BaseInput
                v-model="form.contractScope"
                placeholder="输入合同范围"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="评价小组成员"
              :label-col="{lg: {span: 5}, sm: {span:5}}"
              :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
              prop="evalEmployees"
            >
              <LargeSelect
                ref="LargeSelect"
                v-model="form.evalEmployees"
                :mode="'multiple'"
                :load-date="loadDate"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>

    <div class="page-btn-right-top">
    <!-- <div style="float:right;margin-bottom: 20px"> -->
      <a-button
        :loading="submitLoading"
        type="primary"
        @click="submit('DRAFT')"
      >
        保存草稿
      </a-button>
      <a-button
        :loading="submitLoading"
        class="ml12"
        type="primary"
        @click="submit('SUBMITTED')"
      >
        提交
      </a-button>
      <a-button
        type="primary"
        class="ml12"
        @click="goBack"
      >
        关闭
      </a-button>
    </div>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { getResourceEvaluateDeltails, getAuditForm } from '@/api/project/branchEvaluate'
import { getEmployeesList } from '@/api/commons'
import ARow from 'ant-design-vue/es/grid/Row'
import LargeSelect from '@/components/LargeSelect'

export default {
  name: 'a' + Date.now(),
  components: {
    ARow,
    LargeSelect
  },
  data() {
    return {
      form: {
        contractScope: '',
        evalEmployees: []
      }, // 表单对象
      rules: {
        // 表单验证
        contractScope: [{ required: true, message: '请输入合同范围', trigger: 'blur' }],
        evalEmployees: [{ required: true, message: '请选择分公司人员', trigger: 'change' }]
      },

      id: '',
      dels: {
        // 详情数据
        creater: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        createTime: this.getNowTime(),
        viewName: ''
      },

      scoreIndex: '', // 评分的dataIndex
      scoreIndex1: '', // 评分的dataIndex
      employees: [], // 评价人员
      tableData: [], // 评价表数据
      columnsScore: [], // 评价表头
      // 按钮加载
      submitLoading: false,
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },

 async created() {
    this.id = this.$route.query.id
    this.getResourceEvaluateDeltailsReq()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('design_resource_branch_evaluation')
  },
  computed: {
    score() {
      return this.columnsScore[this.columnsScore.length - 1].dataIndex
    }
  },
  methods: {
    // 获取输入项的最大允许值
    getMaxValue(data) {
      const targetData = this.columnsScore.find((item) => item.code === '4') // 考核评分列
      return (targetData && Number(data[targetData['dataIndex']])) || 0
    },

    // 限制评分输入正整数
    limitNumber(value) {
      if (typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(/\./g, '') : 0
      } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(/\./g, '') : 0
      } else {
        return 0
      }
    },

    // 实时叠加评价总分
    superpositionScore(value) {
      let arr = []
      this.tableData.forEach((item) => {
        if (item[this.score] != undefined) {
          arr.push(parseInt(item[this.score]))
        }
      })
      this.dels.totalScore = eval(arr.join('+'))
      if (this.dels.totalScore < 70) {
        this.dels.assessmentLevel = '不合格'
      } else if (this.dels.totalScore >= 70 && this.dels.totalScore < 80) {
        this.dels.assessmentLevel = '合格'
      } else if (this.dels.totalScore >= 80 && this.dels.totalScore < 90) {
        this.dels.assessmentLevel = '良好'
      } else if (this.dels.totalScore >= 90) {
        this.dels.assessmentLevel = '优秀'
      } else {
        this.dels.assessmentLevel = ''
      }
    },

    // 获取评价详情
    getResourceEvaluateDeltailsReq() {
      getResourceEvaluateDeltails({ id: this.id }).then((res) => {
        this.dels = res.data
        this.dels.viewName = this.dels.branchComName + '/' + this.dels.projectName
        ;(this.dels.creater = JSON.parse(sessionStorage.getItem('ycloud-user_info')).name),
          (this.dels.createTime = this.getNowDate())
        this.columnsScore = res.data.scoreHeader
        this.tableData = res.data.scoreContent
        this.form.contractScope = res.data.contractScope
        this.form.evalEmployees = res.data.evalEmployees
        this.$refs.LargeSelect.addList()
        let obj = {
          dataIndex: 'serial',
          formId: null,
          title: '序号',
          code: '0',
          sort: 0,
          inputType: null,
          scopedSlots: { customRender: 'serial' }
        }
        this.columnsScore.unshift(obj)

        let objScore = {}
        let objScore1 = {}
        this.columnsScore.forEach((item) => {
          objScore = this.columnsScore.filter((item) => item.title == '评分')
          objScore1 = this.columnsScore.filter((item) => item.title == '考核分类')
        })
        objScore[0].scopedSlots = { customRender: 'score' }
        this.scoreIndex = objScore[0].dataIndex
        this.scoreIndex1 = objScore1[0].dataIndex
      })
    },

    submit(type) {
      let arr = []
      let arrys = this.tableData
      for (var i = 0; i < arrys.length; i++) {
        for (var k in arrys[i]) {
          if (this.scoreIndex1 == k) {
            arr.push({
              id: arrys[i].id,
              scoreCont: arrys[i][this.score],
              考核分类: arrys[i][k]
            })
          }
        }
      }
      if (type === 'DRAFT') {
        this.commit(type, arr)
      } else {
        this.$refs.form1.validate((err, value) => {
          if (err) {
            const vm = this
            vm.$confirm({
              title: '提交确认',
              content: '确定提交分公司评价吗？',
              onOk() {
                try {
                  arr.forEach(function (obj, i) {
                    if (obj.scoreCont == undefined) {
                      throw new Error('EndMessage')
                    }
                  })
                } catch (e) {
                  if (e.message == 'EndMessage') {
                    vm.$message.error('评分不能为空，核对后请重新输入！')
                    return
                  }
                }
                if (vm.tableData.length != arr.length) {
                  vm.$message.error('请先输入评分！')
                  return
                }
                vm.commit(type, arr)
              },
              onCancel() {}
            })
          }
        })
      }
    },
    /**
     * @description: 提交
     * @param {void}
     * @return {void}
     */
    commit(type, arr) {
      this.form.id = this.id
      let newData = JSON.parse(JSON.stringify(arr).replace(/scoreCont/g, this.scoreIndex))
      this.form.contentList = newData
      this.form.evaluationTypeCode = '25002'
      this.form.totalScore = this.dels.totalScore
      this.form.assessmentLevel = this.dels.assessmentLevel
      const params = this.$clone(this.form)
      params.auditStatus = type
      getAuditForm(params).then((res) => {
        if (res.code == 200 || res.data.code == 200) {
          this.$message.success('操作成功！')
          if(type =='SUBMITTED') {
            //提交时，返回id
                this.businessId = res.data || this.id;
                this.setProcessConfig = this.processConfig;
                return
            }else{
              this.$multiTab.close(this.$route.fullpath)
          }
        }
      })
    },
    // 获取分公司人员
    async loadDate() {
      try {
        const { data } = await getEmployeesList({ rootOrhId: this.dels.branchComId })
        return data
      } catch (error) {
        return []
      }
    },

    // 评价人员可搜索
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    goBack() {
      this.$multiTab.close(this.$route.fullpath)
    }
  }
}
</script>
